<?php

namespace Pader\DcatAdmin\ChinaDistpicker;

use Dcat\Admin\Admin;
use Dcat\Admin\Grid\Filter\AbstractFilter;
use Illuminate\Support\Arr;

class DistpickerFilter extends AbstractFilter
{

    /**
     * @var string
     */
    protected $view = 'pader-china-distpicker::filter';

    /**
     * @var array
     */
    protected static $js = [
        'vendor/dcat-admin-extensions/pader/dcat-admin-china-distpicker/dist/distpicker.min.js'
    ];

    /**
     * {@inheritdoc}
     */
    public function condition($inputs)
    {
        $value = Arr::get($inputs, $this->column);

        if (!isset($value)) {
            return;
        }

        $this->value = $value;

        $value = $value['district'] ?? $value['city'] ?? $value['province'];

        if (substr($value, -2) != '00') {
            $params = $value;
        } else {
            if (substr($value, -4) == '0000') {
                $end = substr($value, 0, 2).'9999';
            } else {
                $end = substr($value, 0, 4).'99';
            }
            $this->query = 'whereBetween';
            $params = [$value, $end];
        }

        return $this->buildCondition($this->column, $params);
    }

    /**
     * Setup js scripts.
     */
    protected function setupScript()
    {
        $value = old($this->column, $this->value);

        $province = $value['province'] ?? null;
        $city = $value['city'] ?? null;
        $district = $value['district'] ?? null;

        $this->addVariables(compact('province', 'city', 'district'));

        $script = <<<EOT
$("#{$this->id}").distpicker({
  province: '— 省 —',
  city: '— 市 —',
  district: '— 区 —'
});
EOT;
        Admin::script($script);
        Distpicker::requireAssets();
    }

    /**
     * {@inheritdoc}
     */
    public function variables()
    {
        $this->id = 'distpicker-filter-' . uniqid();
        $this->setupScript();
        return parent::variables();
    }

}
